﻿#!/usr/bin/env python
#
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

from google.appengine.dist import use_library
use_library('django', '1.2')
from django.utils import simplejson as json
from google.appengine.api import memcache, users
from google.appengine.ext import db, webapp
from google.appengine.ext.webapp.template import render
from google.appengine.ext.webapp.util import run_wsgi_app



class FiberOpticCable(db.Model):
    author = db.UserProperty()
    remote_addr = db.StringProperty()
    date = db.DateTimeProperty(auto_now_add=True)
    sh_descr = db.StringProperty()
    descr = db.TextProperty()
    typeid = db.IntegerProperty()
    typeuuid = db.StringProperty()
    modnum = db.IntegerProperty()
    fibernum = db.IntegerProperty()

class FiberOptic(db.Model):
    author = db.UserProperty()
    remote_addr = db.StringProperty()
    date = db.DateTimeProperty(auto_now_add=True)
    descr = db.StringProperty()
    FOCtypeid = db.IntegerProperty()
    FOCtypeuuid = db.StringProperty()
    FOCkey = db.StringProperty()
    fibernum = db.IntegerProperty()
    modnum = db.IntegerProperty()
    fibercolor = db.IntegerProperty()
    modcolor = db.IntegerProperty()

class Greeting(db.Model):
    author = db.UserProperty()
    content = db.TextProperty()
    remote_addr = db.TextProperty()
    date = db.DateTimeProperty(auto_now_add=True)

class GetFiberOpticCable(webapp.RequestHandler):
    def get(self):
        user = users.get_current_user()
        #mem_foc = memcache.get('mem_foc')
        #if not mem_foc:
        mem_foc = FiberOpticCable.all().order('-date').fetch(30)
        #    memcache.add('mem_foc', mem_foc)
        context_foc = {
            'user':      user,
            'mem_foc': mem_foc,
            'login':     users.create_login_url(self.request.uri),
            'logout':    users.create_logout_url(self.request.uri),
        }
        tmpl_foc = os.path.join(os.path.dirname(__file__), 'FiberOpticCable.html')
        self.response.out.write(render(tmpl_foc, context_foc))

class ControllerFOC(webapp.RequestHandler):
    def post(self):
        self.response.headers['Content-Type'] = 'application/json'
        
        get_db_foc = FiberOpticCable.all().order('-date').fetch(2)
        self.response.out.write("""{data:[""")
        for p in get_db_foc:
            self.response.out.write("""{"author":"%s","remote_addr":"%s","date":"%s","sh_descr":"%s","descr":"%s","typeid":"%s","typeuuid":"%s","modnum":"%s","fibernum":"%s"},""" % (p.author, p.remote_addr, p.date, p.sh_descr, p.descr, p.typeid, p.typeuuid, p.modnum, p.fibernum))
        self.response.out.write("""],pageInfo:{totalRowNum:1},recordType : 'object'}""")
        
        self.response.out.write("""{data:[{"author":"2846","remote_addr":"10.250.46.242","date":null,"sh_descr":"105330","descr":"0","typeid":"22","typeuuid":null,"modnum":"2","fibernum":"24"}],pageInfo:{totalRowNum:1},recordType : 'object'}""")

    def get(self):
        self.response.headers['Content-Type'] = 'application/json'
        jsonData = {"foo" : "bar"}
        self.response.out.write(json.dumps(jsonData))

class ControllerFOCwr(webapp.RequestHandler):
    def post(self):
        self.response.headers['Content-Type'] = 'application/json'
        #self.response.out.write(self.request.get('_gt_json'))
        request_content = json.loads(self.request.get('_gt_json'))
        for insert_rec in request_content.get('insertedRecords', []):
            #self.response.out.write('____________________________________' + insert_rec.__repr__())
            db_foc = FiberOpticCable()
            db_foc.author = users.get_current_user()
            db_foc.remote_addr = self.request.remote_addr
            #db_foc.date = 
            db_foc.sh_descr = insert_rec['sh_descr']
            db_foc.descr = insert_rec['descr']
            #db_foc.typeid = 
            #db_foc.typeuuid = 
            db_foc.modnum = insert_rec['modnum'] and int(insert_rec['modnum']) or 0
            db_foc.fibernum = insert_rec['fibernum'] and int(insert_rec['fibernum']) or 0
            db_foc.put()

        for delete_rec in request_content.get('deletedRecords', []):
            db.delete(delete_rec['key_str'])

        for update_rec in request_content.get('updatedRecords', []):
            db_foc = db.get(update_rec['key_str'])
            #self.response.out.write('____________________________________' + update_rec.__repr__())
            #db_foc.author = users.get_current_user()
            #db_foc.remote_addr = self.request.remote_addr
            #db_foc.date = 
            db_foc.sh_descr = update_rec['sh_descr']
            db_foc.descr = update_rec['descr']
            #db_foc.typeid = 
            #db_foc.typeuuid = 
            db_foc.modnum = update_rec['modnum'] and int(update_rec['modnum']) or 0
            db_foc.fibernum = update_rec['fibernum'] and int(update_rec['fibernum']) or 0
            db_foc.put()

        get_db_foc = FiberOpticCable.all().order('-fibernum').fetch(20)
        outformat = """{"key_str":"%s","author":"%s","remote_addr":"%s","date":"%s","sh_descr":"%s","descr":"%s","typeid":"%s","typeuuid":"%s","modnum":"%s","fibernum":"%s"}"""
        self.response.out.write("""{data:[""")
        self.response.out.write(
            ','.join([
                    outformat % (str(p.key()), p.author and p.author.email()[:5] or u"Гість", p.remote_addr[:7], str(p.date)[:10], p.sh_descr, p.descr, p.typeid, p.typeuuid, p.modnum, p.fibernum)
                        for p in get_db_foc
                ])
            )
        self.response.out.write("""],pageInfo:{totalRowNum:1},recordType : 'object'}""")
        #self.response.out.write(request_content)
        #self.response.out.write("""{data:[{"author":"Saved", "remote_addr":"10.250.46.242", "date":null, "sh_descr":"105330", "descr":"0","typeid":"22","typeuuid":null,"modnum":"2","fibernum":"24"}], pageInfo:{totalRowNum:1},recordType : 'object'}""")

    def get(self):
        self.response.headers['Content-Type'] = 'application/json'
        jsonData = {"foo" : "bar"}
        self.response.out.write(json.dumps(jsonData))

        #for name in os.environ.keys():
        #    self.response.out.write("%s = %s<br><br>\n" % (name, os.environ[name]))

class MainHandler(webapp.RequestHandler):
    def get(self):
        user = users.get_current_user()
        greetings = memcache.get('greetings')
        if not greetings:
            greetings = Greeting.all().order('-date').fetch(30)
            memcache.add('greetings', greetings)
        context = {
            'user':      user,
            'greetings': greetings,
            'login':     users.create_login_url(self.request.uri),
            'logout':    users.create_logout_url(self.request.uri),
        }
        tmpl = os.path.join(os.path.dirname(__file__), 'index.html')
        self.response.out.write(render(tmpl, context))

class GuestBook(webapp.RequestHandler):
    def post(self):
        greeting = Greeting()
        greeting.author = users.get_current_user()
        greeting.content = self.request.get('content')
        greeting.remote_addr = self.request.remote_addr
        greeting.put()
        memcache.delete('greetings')
        self.redirect('/')

class PrintEnvironmentHandler(webapp.RequestHandler):
    def get(self):
        for name in os.environ.keys():
            self.response.out.write("%s = %s<br><br>\n" % (name, os.environ[name]))


application = webapp.WSGIApplication([
    ( '/', MainHandler),
    ( '/FiberOpticCable.html', GetFiberOpticCable),
    ( '/controller/foc.php', ControllerFOCwr),
    ( '/controller/foc.txt', ControllerFOCwr),
    ( '/sign', GuestBook),
    ( '/prt', PrintEnvironmentHandler),
], debug=True)

def main():
    run_wsgi_app(application)

if __name__ == '__main__':
    main()